package cn.dgiot.fd.quartz;

import java.util.List;

import cn.dgiot.fd.service.IDeviceService;
import cn.dgiot.fd.service.IDeviceStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse;

import cn.dgiot.fd.model.DeviceModel;
import cn.dgiot.fd.model.DeviceStateModel;

/**
 * [更新设备信息]
 * @author
 *
 */
@Component
@Configurable
@EnableScheduling
public class DeviceStateUpdateQuartz{
	
	@Autowired
	private IDeviceStateService deviceStateService;
	@Autowired
	private IDeviceService deviceService;
	
	private static boolean flag = true;

	/**
	 * [每五分钟更新一次设备信息]
	 */
    @Scheduled(cron="* */5 * * * *")
    public void reportCurrent(){
    	if(flag) {
    		flag = false;
    		try {
		    	/** 查询待更新数据列表 */
		    	List<DeviceStateModel> list= deviceStateService.getUpdateDeviceList(new DeviceStateModel());
		    	if(list != null && list.size() > 0) {
		    		for(int i=0;i<list.size(); i++) {
		    			DeviceStateModel updateModel = list.get(i);
		    			DeviceModel deviceModel = new DeviceModel();
		    			deviceModel.setDeviceName(updateModel.getDeviceName());
		    			QueryDeviceDetailResponse response = deviceService.queryDeviceDetail(deviceModel);
		    			if(response != null && response.getSuccess()) {
		    				updateModel.setIotId(response.getData().getIotId());
		    				updateModel.setProductKey(response.getData().getProductKey());
		    				updateModel.setDeviceSecret(response.getData().getDeviceSecret());
		    				updateModel.setState(response.getData().getStatus());
		    				deviceStateService.updateDeviceState(updateModel);
		    			}
		    		}
		    	}
    		}catch(Exception ex) {
    			
    		}
    		flag = true;
    	}
    }
}